/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.tor.tribes.reportserver.ui;

import com.vaadin.data.Validator;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.validator.EmailValidator;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.terminal.UserError;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window.Notification;
import de.tor.tribes.reportserver.ILoginListener;
import de.tor.tribes.reportserver.MyVaadinApplication;
import de.tor.tribes.reportserver.PersistenceImpl;
import de.tor.tribes.reportserver.util.UIUtil;
import de.tor.tribes.types.ZebraUser;

/**
 *
 * @author Torridity
 */
public class LoginScreen extends CustomComponent {

    private GridLayout mainLayout;
    private ILoginListener listener = null;
    private TextField userField;
    private TextField emailField;
    private PasswordField passwordField;
    private PasswordField secondaryPasswordField;
    private Button loginButton;
    private Button registerButton;
    private Button doRegisterButton;
    private Button cancelRegisterButton;

    public LoginScreen(ILoginListener pListener) {
        listener = pListener;
        buildMainLayout();
        setupLoginView();
    }

    private void buildMainLayout() {
        userField = new TextField("Name");
        userField.setWidth("100%");
        userField.setRequired(true);
        userField.setRequiredError("Eingabe wird benötigt");
        StringLengthValidator sl1 = new StringLengthValidator("Benutzername muss mindestens 3 Zeichen lang sein");
        sl1.setMinLength(3);
        userField.addValidator(sl1);

        emailField = new TextField("EMail");
        emailField.setWidth("100%");
        emailField.setRequired(true);
        emailField.setRequiredError("Eingabe wird benötigt");
        //emailField.addValidator(new EmailValidator("Email Adresse ungültig"));

        passwordField = new PasswordField("Passwort");
        passwordField.setWidth("100%");
        passwordField.setRequired(true);
        passwordField.setRequiredError("Eingabe wird benötigt");
        StringLengthValidator sl2 = new StringLengthValidator("Passwort muss mindestens 3 Zeichen lang sein");
        sl2.setMinLength(3);
        passwordField.addValidator(sl2);

        secondaryPasswordField = new PasswordField("Wiederholen");
        secondaryPasswordField.setWidth("100%");
        secondaryPasswordField.setRequired(true);
        secondaryPasswordField.setRequiredError("Eingabe wird benötigt");
        StringLengthValidator sl3 = new StringLengthValidator("Passwort muss mindestens 3 Zeichen lang sein");
        sl3.setMinLength(3);
        secondaryPasswordField.addValidator(sl3);

        loginButton = new Button("Login");
        loginButton.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                login();
            }
        });

        registerButton = new Button("Registrieren");
        registerButton.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                setupRegisterView();
            }
        });
        doRegisterButton = new Button("Registrieren", this, "register");

        cancelRegisterButton = new Button("Abbrechen");
        cancelRegisterButton.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                setupLoginView();
            }
        });
    }

    private void setupLoginView() {
        mainLayout = new UIUtil.GridLayoutBuilder(2, 3).
                addComponent(userField, 0, 0, 2, 1).
                addComponent(passwordField, 0, 1, 2, 1).
                addComponent(loginButton, 0, 2).
                addComponent(registerButton, 1, 2).getLayout();
        userField.setRequired(false);
        passwordField.setRequired(false);
        mainLayout.setSpacing(true);
        setCompositionRoot(mainLayout);
    }

    private void setupRegisterView() {
        mainLayout = new UIUtil.GridLayoutBuilder(2, 5).
                addComponent(userField, 0, 0, 2, 1).
                addComponent(emailField, 0, 1, 2, 1).
                addComponent(passwordField, 0, 2, 2, 1).
                addComponent(secondaryPasswordField, 0, 3, 2, 1).
                addComponent(doRegisterButton, 0, 4).
                addComponent(cancelRegisterButton, 1, 4).
                getLayout();

        userField.setRequired(true);
        passwordField.setRequired(true);
        mainLayout.setSpacing(true);
        setCompositionRoot(mainLayout);
    }

    public void register() {
        String password = (String) passwordField.getValue();
        String passwordCheck = (String) secondaryPasswordField.getValue();
        String name = (String) userField.getValue();
        String email = (String) emailField.getValue();

        if (!userField.isValid() || !passwordField.isValid() || !secondaryPasswordField.isValid() || !emailField.isValid()) {
            return;
        }

        if (!password.equals(passwordCheck)) {
            secondaryPasswordField.setComponentError(new UserError("Passwörter stimmen nicht überein"));
            return;
        } else {
            secondaryPasswordField.setComponentError(null);
        }
        name = name.toLowerCase();
        email = email.toLowerCase();

        if (((MyVaadinApplication)getApplication()).getPersistence().userExists(name, email)) {
            getWindow().showNotification("Fehler", "Es existiert bereits ein Benutzer mit dem gewählten Namen oder der gewählten eMail Adresse.", Notification.TYPE_ERROR_MESSAGE);
            return;
        }

        ZebraUser user = new ZebraUser();
        user.setName(name);
        user.setPlainPassword(password);
        user.setEmail(email);
        ((MyVaadinApplication)getApplication()).getPersistence().persistUser(user);
        setupLoginView();
        getWindow().showNotification("Benutzer erstellt", "Der Benutzer wurde erfolgreich erstellt.", Notification.TYPE_TRAY_NOTIFICATION);
    }

    private void login() {
        String name = (String) userField.getValue();
        name = name.toLowerCase();
        ZebraUser foundUser = ((MyVaadinApplication)getApplication()).getPersistence().getUser(name, (String) passwordField.getValue());
        listener.fireLoginEvent(foundUser);
    }
}
